﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

public class CustomTools : EditorWindow
{
    [MenuItem("Tools/BatchAddLODGroup")]
    public static void BatchAddLODGroup()
    {
        string path = string.Format("{0}/GameAssets/", Application.dataPath);
        string targetPath = EditorUtility.OpenFolderPanel("加载路径", path, "");
        if (targetPath == "" || targetPath == null)
            return;
        string[] filesPath = Directory.GetFiles(targetPath, "*.prefab", SearchOption.AllDirectories);
        for (int i = 0; i < filesPath.Length; i++)
        {
            filesPath[i] = filesPath[i].Substring(filesPath[i].IndexOf("Assets"));
            GameObject prefab = AssetDatabase.LoadAssetAtPath(filesPath[i], typeof(GameObject)) as GameObject;
            GameObject go = PrefabUtility.InstantiatePrefab(prefab) as GameObject ;
            LODGroup lodGroup = go.GetComponent<LODGroup>();
            if(lodGroup == null)
            {
                lodGroup = go.AddComponent<LODGroup>();
            }
            LOD[] oldLods = lodGroup.GetLODs();
            lodGroup.fadeMode = LODFadeMode.CrossFade;
            LOD[] lods = new LOD[1];
            lods[0].screenRelativeTransitionHeight = 0.15f;
            lods[0].renderers = go.GetComponents<Renderer>();
            lodGroup.SetLODs(lods);
            bool isSuccess = false;
            PrefabUtility.SaveAsPrefabAsset(go, filesPath[i], out isSuccess);
            if (!isSuccess)
            {
                Debug.LogError("保存预设失败-->" + filesPath[i]);
            }
            GameObject.DestroyImmediate(go);
        }
        AssetDatabase.SaveAssets();
    }

    [MenuItem("Tools/BatchRemoveLODGroup")]
    public static void BatchRemoveLODGroup()
    {
        string path = string.Format("{0}/GameAssets/", Application.dataPath);
        string targetPath = EditorUtility.OpenFolderPanel("加载路径", path, "");
        if (targetPath == "" || targetPath == null)
            return;
        string[] filesPath = Directory.GetFiles(targetPath, "*.prefab", SearchOption.AllDirectories);
        for (int i = 0; i < filesPath.Length; i++)
        {
            filesPath[i] = filesPath[i].Substring(filesPath[i].IndexOf("Assets"));
            GameObject prefab = AssetDatabase.LoadAssetAtPath(filesPath[i], typeof(GameObject)) as GameObject;
            GameObject go = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
            LODGroup lodGroup = go.GetComponent<LODGroup>();
            if (lodGroup != null)
            {
                Component.DestroyImmediate(lodGroup);
            }
            bool isSuccess = false;
            PrefabUtility.SaveAsPrefabAsset(go, filesPath[i], out isSuccess);
            if (!isSuccess)
            {
                Debug.LogError("保存预设失败-->" + filesPath[i]);
            }
            GameObject.DestroyImmediate(go);
        }
        AssetDatabase.SaveAssets();
    }
}
